package a202110.day10;

/**
 * 搜索插入位置
 * <p>
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。
 * 如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * 请必须使用时间复杂度为 O(log n) 的算法。
 * <p>
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 * <p>
 * 输入: nums = [1,3,5,6], target = 2
 * 输出: 1
 * <p>
 * 输入: nums = [1,3,5,6], target = 7
 * 输出: 4
 * <p>
 * 输入: nums = [1,3,5,6], target = 0
 * 输出: 0
 * <p>
 * 输入: nums = [1], target = 0
 * 输出: 0
 * <p>
 * 提示:
 * 1 <= nums.length <= 104
 * -104 <= nums[i] <= 104
 * nums 为无重复元素的升序排列数组
 * -104 <= target <= 104
 *
 * @author yousj
 * @since 2021/10/24
 */
public class Main04 {

    public static void main(String[] args) {
        int[] nums = {1, 3, 5, 6, 7, 9};
        System.out.println(searchInsert(nums, 3));
    }

    private static int searchInsert(int[] nums, int target) {
        int mid, low = 0, high = nums.length;
        while (low < high) {
            mid = (low + high) >> 1;
            if (nums[mid] >= target) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }
        return low;
    }

    private static int searchInsert1(int[] nums, int target) {
        int mid, low = 0, high = nums.length - 1;
        while (low <= high) {
            mid = ((high - low) >> 1) + low;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return low;
    }
}
